package com.hanxiaozhang.juc.no2threadpool;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 * ThreadPoolExecutor.shutdown() VS ThreadPoolExecutor.shutdownNow()
 * 调用ThreadPoolExecutor#shutdown()后，线程池状态从RUNNING转变为SHUTDOWN。
 * 调用ThreadPoolExecutor#shutdownNow()后，线程池状态将会从RUNNING转变为STOP。
 * <p>
 * 拓展：优雅关闭线程池
 * <p>
 * 如果线程池任务执行结束，awaitTermination()将会返回true，否则当等待时间超过指定时间后将会返回false
 *
 * @author hanxinghua
 * @create 2024/5/14
 * @since 1.0.0
 */
public class No1ShutdownAndShutdownNowNode {

    private static ExecutorService executor = Executors.newFixedThreadPool(3);

    public static void main(String[] args) {

        for (long i = 1; i < 20; i++) {
            long finalI = i;
            executor.submit(() -> {
                try {
                    System.out.println("开始执行-" + finalI);
                    TimeUnit.MILLISECONDS.sleep((10 * finalI));
                    System.out.println("执行结束-" + finalI);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        // executor.shutdown();
        List<Runnable> runnables = executor.shutdownNow();
        System.out.println();
    }


    /**
     * 优雅关闭
     *
     * @param executor
     */
    private static void gracefulShutdown(ExecutorService executor) {

        // 禁止提交新任务
        executor.shutdown();
        try {
            // 等待 60 s
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                // 调用 shutdownNow 取消正在执行的任务
                executor.shutdownNow();
                // 再次等待 60 s，如果还未结束，可以再次尝试，或则直接放弃
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    System.err.println("线程池任务未正常执行结束");
                }
            }
        } catch (InterruptedException ie) {
            // 重新调用 shutdownNow
            executor.shutdownNow();
        }
    }

}
